//
//  WHHomeController.m
//  SquirrelSeller
//
//  Created by 邓伟浩 on 2018/12/29.
//  Copyright © 2018 邓伟浩. All rights reserved.
//

#import "WHHomeController.h"
#import "WHHomeTopView.h"
#import "WHViewGetCell.h"
#import "WHMineController.h" // 我的
#import "WHMyWalletController.h" // 我的钱包
#import "WHAddShopController.h" // 新增门店
#import "WHNoDataViewTool.h"

@interface WHHomeController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIImageView *topBackImageView;
@property (nonatomic, strong) WHHomeTopView *headerView;
@property (nonatomic, strong) UITableView *dataTableView;

@property (nonatomic, strong) UIView *hudView; // headerView上的遮盖
@property (nonatomic, assign) BOOL isHideView; // 是否隐藏headerView
@property (nonatomic, assign) CGFloat headerViewH; // headerView高度

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@end

@implementation WHHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"首页";
    self.naviType = NaviTypeClear;
    [self initParams];
    [self setUpUI];
    [self setUpNavigationItems];
    
    [self headerRereshing];
    [self registerNotification];
}

- (void)registerNotification {
    [kNotificationCenter addObserver:self
                            selector:@selector(headerRereshing)
                                name:KUserDetailInfoChange
                              object:nil];
}

- (void)initParams {
    _page = 1;
    _dataArray = @[].mutableCopy;
}

- (void)setUpNavigationItems {
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 40, kNavBarHeight);
    [leftButton addTarget:self action:@selector(toMine:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:IMAGE_NAMED(@"home_mine_icon") forState:UIControlStateNormal];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    rightButton.frame = CGRectMake(0, 0, 40, kNavBarHeight);
    NSAttributedString *attStr = [[NSAttributedString alloc] initWithString:@"新增门店" attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(16)), NSForegroundColorAttributeName:KWhiteColor}];
    [rightButton setAttributedTitle:attStr forState:UIControlStateNormal];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [rightButton addTarget:self action:@selector(addShop:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)setUpUI {
    [self setUpBackView];
    
    self.headerViewH = ceil(kRealwidth(315));
    
    [self setUpTopView];
    [self setUpHudView];
    [self setUpTableView];
    
    [self.view bringSubviewToFront:self.headerView];
}

- (void)setUpBackView {
    [self.view addSubview:({
        _topBackImageView = [[UIImageView alloc] init];
        _topBackImageView.contentMode = UIViewContentModeScaleAspectFill;
        _topBackImageView.userInteractionEnabled = YES;
        _topBackImageView.image = IMAGE_NAMED(@"mywallet_back_img");
        
        _topBackImageView;
    })];
    [_topBackImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
}

- (void)setUpTopView {
    
    WHHomeTopView *headerView = [[WHHomeTopView alloc] init];
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(self.view);
        make.height.mas_equalTo(self.headerViewH+kTopHeight);
    }];
    _headerView = headerView;
    kWeakSelf(self);
    headerView.balanceTap = ^{
        [weakself toBalance];
    };
    
}

- (void)setUpHudView {
    UIView *hudView = [[UIView alloc] init];
    hudView.backgroundColor = [UIColor blackColor];
    hudView.alpha = 0.6;
    [self.view addSubview:hudView];
    [hudView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(self.headerView);
        make.size.mas_equalTo(self.headerView);
    }];
    _hudView = hudView;
}

- (void)setUpTableView {
    UITableView *dataTableView = [[UITableView alloc] initWithFrame:kScreen_Bounds style:UITableViewStylePlain];
    dataTableView.delegate = self;
    dataTableView.dataSource = self;
    [self.view addSubview:dataTableView];
    
    [dataTableView registerClass:[WHViewGetCell class] forCellReuseIdentifier:NSStringFromClass([WHViewGetCell class])];
    
    dataTableView.tableFooterView = [UIView new];
    dataTableView.backgroundColor = KClearColor;
    dataTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    dataTableView.contentInset = UIEdgeInsetsMake(self.headerViewH, 0, 0, 0);
    dataTableView.tableHeaderView = [self tableHeaderView];
    dataTableView.tableFooterView = [self tableFooterView];
    
    [dataTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.equalTo(@kTopHeight);
    }];
    [dataTableView scrollToTop];
    
    kWeakSelf(self);
    dataTableView.mj_header = [WHGifHeader headerWithRefreshingBlock:^{
        [weakself headerRereshing];
    }];
    
    dataTableView.mj_footer = [WHGifFooter footerWithRefreshingBlock:^{
        [weakself footerRereshing];
    }];
    dataTableView.mj_footer.hidden = YES;
    
    _dataTableView = dataTableView;
}

- (UIView *)tableHeaderView {
    UIView *tableHeaderView = [[UIView alloc] init];
    
    tableHeaderView.backgroundColor = KWhiteColor;
    tableHeaderView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(60));
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:tableHeaderView.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(12 ,12)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = tableHeaderView.bounds;
    maskLayer.path = maskPath.CGPath;
    tableHeaderView.layer.mask = maskLayer;
    
    UILabel *tipsLabel = [[UILabel alloc] init];
    [tableHeaderView addSubview:tipsLabel];
    tipsLabel.textAlignment = NSTextAlignmentCenter;
    tipsLabel.textColor = CFontContentLightGrayColor;
    tipsLabel.font = SYSTEMFONT(kRealwidth(15));
    tipsLabel.text = @"——— 今日合作门店看板 ———";
    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(tableHeaderView);
    }];
    
    return tableHeaderView;
}

- (UIView *)tableFooterView {
    UIView *tableFooterView = [[UIView alloc] init];
    tableFooterView.backgroundColor = KWhiteColor;
    
    CGFloat height = kScreenHeight - kTopHeight - kRealwidth(60) - _dataArray.count*kRealwidth(70);
    if (height > 0) {
        tableFooterView.frame = CGRectMake(0, 0, KScreenWidth, height);
    } else {
        tableFooterView.frame = CGRectMake(0, 0, KScreenWidth, 0);
    }
    
    return tableFooterView;
}

- (void)showNoDataView {
    self.dataTableView.tableFooterView = [self noMoreDataFooterView];
}

- (void)hideNoDataView {
    self.dataTableView.tableFooterView = [self tableFooterView];
}

- (UIView *)noMoreDataFooterView {
    UIView *tableFootView = [[UIView alloc] init];
    tableFootView.backgroundColor = KWhiteColor;
    CGFloat height = kScreenHeight - kTopHeight - kRealwidth(60);
    tableFootView.frame = CGRectMake(0, 0, KScreenWidth, height);
    
    [WHNoDataViewTool addNodataViewAt:tableFootView imageName:@"png_nodataView" topOffset:kRealwidth(50) tipsLabelText:@"暂无数据" tapAction:nil];
    
    return tableFootView;
}

- (void)headerRereshing {
    [self getStationBypageNumber:1 completion:^(BOOL isSucess, BOOL isLast) {
        [self.dataTableView.mj_header endRefreshing];
        if (isSucess) {
            _page = 1;
            self.dataTableView.mj_footer.hidden = NO;
            if (isLast) {
                self.dataTableView.mj_footer.hidden = YES;
            } else {
                [self.dataTableView.mj_footer resetNoMoreData];
            }
        }
    }];
}

- (void)footerRereshing {
    [self getStationBypageNumber:(_page+1) completion:^(BOOL isSucess, BOOL isLast) {
        if (isSucess) {
            if (isLast) {
                [self.dataTableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                _page = _page + 1;
                [self.dataTableView.mj_footer endRefreshing];
            }
            
        } else {
            [self.dataTableView.mj_footer endRefreshing];
        }
        
    }];
    
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WHViewGetCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHViewGetCell class]) forIndexPath:indexPath];
    WHStationModel *statinModel = _dataArray[indexPath.row];
    cell.stationModel = statinModel;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(70);
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.headerView.hidden = NO;
    [self.view insertSubview:self.headerView atIndex:1];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if (self.isHideView) {
        self.headerView.hidden = self.isHideView;
    } else {
        self.headerView.hidden = self.isHideView;
        [self.view bringSubviewToFront:self.headerView];
    }
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        CGFloat offsetY = scrollView.contentOffset.y;
        if (offsetY <= -self.headerViewH*0.5) {
            self.isHideView = NO;
            [self.dataTableView setContentOffset:CGPointMake(0, -self.headerViewH) animated:YES];
        }
        if (offsetY > -self.headerViewH*0.5 && offsetY <= 0) {
            self.isHideView = YES;
            [self.dataTableView setContentOffset:CGPointZero animated:YES];
        }
        if (offsetY > 0) {
            self.isHideView = YES;
        }
        
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y <= -self.headerViewH) {
        [self.view bringSubviewToFront:self.headerView];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat scale = (offsetY + self.headerViewH) / (self.headerViewH+10);
    if (scale > 0.6) {
        scale = 0.6;
    }
    self.hudView.alpha = scale;
    
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    if (velocity.y != 0) {
        if (velocity.y > 0) {
            if (!self.isHideView) {
                self.isHideView = YES;
                CGPoint targetOffset = CGPointZero;
                targetContentOffset->x = targetOffset.x;
                targetContentOffset->y = targetOffset.y;
            }
        }
        
    }
}

#pragma mark - —————— 事件 ——————
- (void)toMine:(UIButton *)button {
    WHMineController *mine = [[WHMineController alloc] init];
    [self.navigationController pushViewController:mine animated:YES];
}

- (void)addShop:(UIButton *)button {
    WHAddShopController *addShop = [[WHAddShopController alloc] init];
    addShop.shopType = ShopTypeAdd;
    [self.navigationController pushViewController:addShop animated:YES];
}

- (void)toBalance {
    WHMyWalletController *myWallet = [[WHMyWalletController alloc] init];
    [self.navigationController pushViewController:myWallet animated:YES];
}

#pragma mark - —————— 接口 ——————
- (void)getStationBypageNumber:(int)pageNumber completion:(void (^)(BOOL isSucess, BOOL isLast))completion {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_selectList);
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          @(pageNumber), @"pageNum",
                          nil];
    
    [WHNetworkManager requestWithURL:postURL parameters:dict isUpData:YES Success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if (ValidDict(responseObject)) {
            NSNumber *errCode = responseObject[@"errcode"];
            NSString *errorMsg = responseObject[@"errmsg"];
            if (errCode.intValue == 0) {
                NSDictionary *object = responseObject[@"retobj"];
                NSString *banlance = object[@"banlance"];
                NSString *todayIntoStatus = object[@"todayIntoStatus"];
                NSString *todayBanlance = object[@"todayBanlance"];
                
                NSDictionary *pageDict = object[@"page"];
                
                _headerView.balanceMoney = ValidStr(banlance)?banlance:@"数据异常";
                _headerView.inCount = ValidStr(todayIntoStatus)?todayIntoStatus:@"数据异常";
                _headerView.payCount = ValidStr(todayBanlance)?todayBanlance:@"数据异常";
                
                if (pageNumber == 1) {
                    [_dataArray removeAllObjects];
                }
                
                NSArray *stations = pageDict[@"data"];
                if (stations.count == 0) {
                    if (completion) {
                        [self.dataTableView reloadData];
                        completion(YES, YES);
                    }
                    if (pageNumber == 1) {
                        DLog(@"没有数据");
                        [self showNoDataView];
                    }
                    return;
                }
                NSArray *tempStationArray = [NSArray modelArrayWithClass:[WHStationModel class] json:stations];
                [self.dataArray addObjectsFromArray:tempStationArray];
                [self.dataTableView reloadData];
                
                [self hideNoDataView];
                
                if (completion) {
                    completion(YES, NO);
                }
                
            } else {
                [WHView showMessage:errorMsg inView:self.view];
                if (completion) {
                    completion(NO, NO);
                }
            }
        }
    } failure:^(NSError *error) {
        if (completion) {
            completion(NO, NO);
        }
    }];
}

@end

